<template>
  <panel :title="title">
    <el-table
      :data="tableData"
      style="width: 100%"
      ref="myTable"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="account" label="账号"> </el-table-column>
      <el-table-column prop="userGroup" label="用户组"> </el-table-column>
      <el-table-column label="创建时间">
        <template slot-scope="scope">
          {{ scope.row.ctime | filterDate }}
        </template>
      </el-table-column>

      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="warning"
            @click="handleEdit(scope.$index, scope.row)"
            >编辑</el-button
          >
          <el-popconfirm
            confirm-button-text="确定"
            cancel-button-text="取消"
            confirm-button-type="text"
            icon="el-icon-info"
            icon-color="red"
            title="您确定要删除账号吗？"
            @confirm="handleDelete(scope.$index, scope.row)"
          >
            <el-button slot="reference" size="mini" type="danger"
              >删除</el-button
            >
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[1, 3, 5, 10, 20]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>

    <div class="button">
      <el-button type="danger" size="small" @click="batchDelAccount"
        >批量删除</el-button
      >
      <el-button type="warning" size="small" @click="cancelSelect"
        >取消选择</el-button
      >
    </div>

    <!-- 编辑弹出模态框 -->
    <el-dialog
      title="编辑账号"
      :visible.sync="dialogVisible"
      width="320px"
      :before-close="handleClose"
    >
      <!-- 表单 -->
      <el-form
        ref="editForm"
        :model="editForm"
        label-width="70px"
        :rules="rules"
      >
        <el-form-item label="账号" prop="account">
          <el-input v-model="editForm.account" class="account"></el-input>
        </el-form-item>

        <el-form-item label="用户组" prop="userGroup">
          <el-select v-model="editForm.userGroup" placeholder="请选择用户组">
            <el-option value="超级管理员"></el-option>
            <el-option value="普通管理员"></el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogVisible = false">取 消</el-button>
        <el-button size="small" type="warning" @click="saveEditAccount"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </panel>
</template>

<script>
import Panel from "@/components/panel/Panel.vue";

import {
  getAccountList,
  editAccount,
  deleteAccount,
  batchDelete,
} from "@/api/user";

// 引入工具函数
import { normalizeDate, accountvalidator } from "@/utils/tools";
export default {
  inject: ["reload"],
  data() {
    const checkEditAccount = (rule, value, callback) => {
      accountvalidator(rule, value, callback);
    };
    return {
      title: "账号列表",
      tableData: [
        // {
        //   id: 1,
        //   account: "小貂蝉",
        //   userGroup: "超级管理员",
        //   ctime: "2019/10/10",
        // },
      ],
      currentPage: 1, //当前页数
      total: 0,
      pageSize: 5,
      dialogVisible: false,
      editForm: {
        account: "",
        userGroup: "",
        id: "",
      },
      ids: [],
      rules: {
        account: {
          validator: checkEditAccount,
          required: true,
          trigger: "blur",
        },
        userGroup: {
          required: true,
          message: "请选择用户组",
          trigger: "change",
        },
      },
    };
  },
  components: {
    Panel,
  },
  methods: {
    //   每页信息个数改变
    handleSizeChange(item) {
      this.pageSize = item;
      this.accountList();
    },
    //   当前页改变时触发
    handleCurrentChange(item) {
      this.currentPage = item;
      this.accountList();
    },
    handleSelectionChange(item) {
      this.ids = item.map((v) => {
        return v.id;
      });
    },
    handleSize() {
      this.reload();
    },
    //解决编辑
    handleEdit(index, row) {
      //点击编辑按钮 弹出一个弹窗
      this.dialogVisible = true;

      this.editForm.account = row.account;
      this.editForm.userGroup = row.userGroup;
      this.editForm.id = row.id;
    },
    // 删除
    async handleDelete(index, row) {
      try {
        let res = await deleteAccount(row.id);

        if (res.data.code === 0) {
          this.accountList();
        }
      } catch (err) {
        console.log(err);
      }
    },
    // 批量删除
     batchDelAccount() {
      if (!this.ids.length || !this.ids) {
        this.$message.error("请选择需要删除的账号");
        return;
      }

      // 在批量删除前 弹出一个确认框提示
      this.$confirm("此操作将永久删除这些账号, 是否继续?", "温馨提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          try {
            let res = await batchDelete(JSON.stringify(this.ids));
            if (res.data.code === 0) {
              this.accountList();
            }
          } catch (err) {
            console.log(err);
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    handleClose(done) {
      this.$confirm("确认取消编辑？")
        .then((_) => {
          done(); //调用关闭函数  关闭所有窗口
        })
        .catch((_) => {});
    },
    cancelSelect() {
      this.$refs.myTable.clearSelection();
    },

    // 提交编辑账号后的信息
    async saveEditAccount() {
      this.dialogVisible = false;

      // 发送ajax请求
      try {
        let res = await editAccount(this.editForm);

        if (res.data.code === 0) {
          this.accountList();
        }
      } catch (err) {
        console.log(err);
      }
    },

    // 获取列表数据
    async accountList() {
      try {
        let res = await getAccountList({
          currentPage: this.currentPage,
          pageSize: this.pageSize,
        });

        let { total, data } = res.data;

        // data.forEach(item => {
        //   item.ctime = normalizeDate(item.ctime)
        // })
        // 当返回的data数组长度为0说明当前没有数据了
        // 并且当前页面不是第一页时 可以把前一页的数据显示
        if (!data.length && this.currentPage != 1) {
          this.currentPage -= 1;
          this.accountList();
        }


        this.total = total;
        this.tableData = data;
      } catch (err) {
        console.log(err);
      }
    },
  },
  filters: {
    filterDate(time) {
      return normalizeDate(time);
    },
  },
  created() {
    this.accountList();
  },
  mounted() {
    window.addEventListener("resize", this.handleSize);
  },

  beforeDestroy() {
    window.removeEventListener("resize", this.handleSize);
  },
};
</script>

<style lang="less" scoped>
@media screen and (max-width: 900px) {
  /deep/ .el-table .cell {
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
  }

  .el-button--danger {
    margin-left: 0;
    margin-top: 5px;
  }
}

.pagination {
  margin-top: 20px;
}

.button {
  margin-top: 20px;
}

.account {
  width: 200px;
}

.el-button--danger {
  margin-left: 10px;
}
</style>